<?php
namespace addons\member\models;
use system\Model;

class MemberFieldsModel extends Model{
	/**
	 * 获取用户存储的字段信息
	 * @param int $uid
	 * @param string $field
	 * @author Colin <amcolin@126.com>
	 * @date 2022-02-08 下午9:40
	 * @return array
	 */
	public function getValue($uid = 0 , $field = ''){
		return $this->where(['uid' => $uid , 'field' => $field])->find();
	}

	/**
	 * 获取用户存储的字段（所有）
	 * @param int $uid
	 * @return array
	 * @author Colin <amcolin@126.com>
	 * @date 2022-02-08 下午9:41
	 */
	public function getValues($uid = 0){
		return $this->where(['uid' => $uid])->field('name,`value`')->select(true)->toArray('name' , 'value');
	}

	/**
	 * 保存字段
	 * @param int $uid
	 * @param array $fields
	 * @author Colin <amcolin@126.com>
	 * @date 2022-02-08 下午9:44
	 */
	public function saveValues($uid = 0 , $fields = []){
		foreach ($fields as $field => $val){
			$value = $this->getValue($uid , $val);
			$map = ['uid' => $uid , 'field' => $field];
			if ($value){
				$this->where($map)->update(['value' => $val]);
			}else{
				$map['value'] = $val;
				$this->insert($map);
			}
		}
	}
}